<?php
namespace cosocket\application;

use cosocket\application\Application;
use cosocket\application\managers\ConnectorManager;

class Handler
{
    private $application;

    public function __construct()
    {
    }

    public function processFrame($frame, $ws, $request)
    {
        $input = json_decode($frame->data, true);
        if (empty($input["c"]) || empty($input["m"])) {
            return;
        }
        $this->handleMessage($frame, $ws, $request);
    }

    public function handleMessage($frame, $ws, $request)
    {
        $input = json_decode($frame->data, true);
        if (empty($input) || empty($input['c']) || empty($input['m'])) {
            return;
        }

        $data = $input["data"];
        $uid = intval($data['uid']);
        if ($uid > 0) {
            ConnectorManager::set_fd($uid, $ws);
        }
        $application = new Application();
        $clientInfo = [
            'remote_ip' => empty($request->header['x-real-ip'])
                ? $request->header['x-forwarded-for']
                : $request->header['x-forwarded-for']
        ];
        $application->run($input, $clientInfo);

        unset($application);
    }

    public function handleClose($frame, $ws, $reason = "")
    {
        ConnectorManager::close_by_ws($ws);
    }
}